#include "BacteriaMob.h"
#include "Level.h"
#include "Player.h"
#include "ImgMgr.h"

BacteriaMob::BacteriaMob()
{

}

void BacteriaMob::init(sf::Vector2f position, ImgMgr *imageManager)
{
    m_direction = 1;
    m_heart = 1;
    m_maxHeart = 1;
    m_skin[0] = imageManager->getSprite(57);
    m_skin[1] = imageManager->getSprite(58);
    m_skin[2] = imageManager->getSprite(59);
    m_skin[3] = imageManager->getSprite(60);

    int e = 0;
    while(e < 4)
    {
        m_skin[e].setScale(2, 2);
        e++;
    }
    m_changeTime = random(1000, 2000);
    setPosition(position);
    Mob::init(position, imageManager);
}

float BacteriaMob::random(float a, float b)
{
    return ( rand()/(double)RAND_MAX ) * (b-a) + a;
}

void BacteriaMob::maj(Player *player, Level *level)
{
    if(m_clockChange.getElapsedTime().asMilliseconds() > m_changeTime)
    {
        m_direction = random(0.6, 2.4);
        m_changeTime = random(1000, 2000);
        m_clockChange.restart();
    }
    if(m_direction == 1)
    {
        if(m_clockFrame.getElapsedTime().asMilliseconds() > 250)
        {
            m_currentRender++;
            if(m_currentRender < 2 || m_currentRender > 3)
                m_currentRender = 2;
            m_clockFrame.restart();
        }
        if(!level->entityCollisionTile(getPosition(), 1, 1))
            m_skin[m_currentRender].move(-2, 0);
        else
            m_direction = 2;
    }
    else if(m_direction == 2)
    {
        if(m_clockFrame.getElapsedTime().asMilliseconds() > 250)
        {
            m_currentRender++;
            if(m_currentRender < 0 || m_currentRender > 1)
                m_currentRender = 0;
            m_clockFrame.restart();
        }
        if(!level->entityCollisionTile(getPosition(), 1, 2))
            m_skin[m_currentRender].move(2, 0);
        else
            m_direction = 1;
    }

    int xPlayer = player->getPosition().x;
    int yPlayer = player->getPosition().y;
    if(xPlayer + 27 > getPosition().x + 5 && xPlayer + 5 < getPosition().x + 27 && yPlayer + 27 > getPosition().y + 5 && yPlayer + 5 < getPosition().y + 27)
    {
        if(m_clockTick.getElapsedTime().asMilliseconds() > 1000)
        {
            player->modifyHeart(-1);
            m_clockTick.restart();
        }
    }

    int e = 0;
    while(e < 4)
    {
        if(e != m_currentRender)
            m_skin[e].setPosition(m_skin[m_currentRender].getPosition());
        e++;
    }
    Mob::maj(player, level);
}
